﻿function convertAnswerToArr(str) {
    var arr = [];
    if (str.length > 0) {
        var a1 = str.split('|');
        for (var i = 0; i < a1.length; i++) {
            var a2 = a1[i].split('.');
            arr[parseInt(a2[0]) - 1] = a2[1];
        }
    }
    return arr;
}

function getTimePast(accessDate) {
    var tmp = new Date();
    var millisec = tmp - accessDate;
    var hr = parseInt(millisec / 1000 / 3600);
    var min = parseInt((millisec - hr * 1000 * 3600) / 1000 / 60);
    var sec = parseInt((millisec - hr * 1000 * 3600 - min * 1000 * 60) / 1000);

    var str = sec.toString() + "秒";
    if (min > 0) str = min.toString() + "分钟" + str;
    if (hr > 0) str = hr.toString() + "小时" + str;

    return str;
}

function convertAnswerToStr(arr) {
    var str = "";
    for (var i = 0; i < arr.length; i++) {
        //入库格式：questionID.optionId|...
        str += (i + 1).toString() + '.' + arr[i];
        if (i < arr.length - 1) {
            str += "|";
        }
    }
    return str;
}

//首先我们必须要保证问题ID是从1开始按顺序的
var curid = 0;
var questions;
var answers = []; //key:curid,value:qid.optid
if ($.cookie(cookienm_questionnaire_useranswer) != undefined) {
    answers = convertAnswerToArr($.cookie(cookienm_questionnaire_useranswer));
}
var accessDate = new Date();
var lastsecdpast = 0;

$(function () {
    $("#content").hide();
    $.ajaxSetup({
        type: "post",
        dataType: "json",
        httpMethod: "POST",
        contentType: "application/json;charset=utf-8"
    });

    $.post(
        svcaddr + "GetQuestionnaireData",
        '{"id":"1"}',
         function (response) {
             var qn = eval("(" + response.d + ")");
             var qs = qn.questions;
             var options = qn.options;

             var showSubmit = function () {
                 $('#btnSubmit').show().click(function () {
                     if ($('input[name="option"]:checked').length <= 0) {
                         $('#err').text("您还没选择");
                         return;
                     }
                     $('#err').text("");

                     // 记录用户COOKIEID，以此为凭证入库
                     window.location.href = "processsignup.aspx";
                 });
             };

             var setCookies = function () {
                 $.cookie(cookienm_questionnaire_useranswer, convertAnswerToStr(answers));
                 var curDate = new Date();
                 $.cookie(cookienm_secondpast, parseInt((curDate - accessDate) / 1000));
             };
             var removeCookies = function () {
                 $.cookie(cookienm_questionnaire_useranswer, null);
                 $.cookie(cookienm_secondpast, null);
             }

             //渲染当前问题
             var renderQuestion = function (nav, ischanged) {
                 this.blur();
                 //若为上一步
                 if ("prev" == nav) {
                     if (curid > 0) curid--;
                 }
                 //若为下一步（自动跳转或下一题）
                 else if ("next" == nav) {
                     if ($('input[name="option"]:checked').length <= 0) {
                         $('#err').text("您还没选择");
                         return;
                     }
                     if (ischanged) {
                         answers[curid] = $('input[name="option"]:checked').attr("rid");
                         setCookies();
                     }

                     $('#err').text("");
                     curid++;
                 }

                 if (qn.enableNext) { $('#next').show(); }
                 if (qn.enablePrev) { $('#prev').show(); }


                 if (answers[curid] != undefined) {
                     $('input[id="option_' + answers[curid] + '"]').prop("checked", true);
                 }

                 //若到最后一步，停留最后一步，并显示提交按钮
                 if (curid >= qs.length - 1) {
                     showSubmit();
                     //隐藏下一步
                     $('#next').hide();
                     $('#question').text(qs.length + '/' + qs.length + ':  ' + qs[qs.length - 1].content);
                 }
                 //否则则显示下一题，并提取之前保存的选项
                 else {
                     //第一步不显示上一页
                     if (curid <= 0) {
                         curid = 0;
                         $('#prev').hide();
                     }
                     $('#question').text((parseInt(curid) + 1).toString() + '/' + qs.length + ':  ' + qs[curid].content);
                     $('input[name="option"]').prop('checked', false);
                 }
             } // end of var renderQuestion

             $('#load').hide();
             $('#prev').hide();
             $('#next').hide();
             $('#btnSubmit').hide();
             $('#content').show();

             $('#qname').text(qn.name);
             for (var i = 0; i < options.length; i++) {
                 //设置问题选项
                 $('#select').append('<input id="option_' + options[i].id + '" rid="' +
                             options[i].id + '" type="radio" name="option" value="' +
                             options[i].value + '">' +
                             options[i].content);
             }

             //跳转到最后填写
             if (answers.length > 0) {
                 curid = answers.length;
                 $('#msg').text('您已经在上次完成到第' + curid + '题，请继续填写。');
                 if (answers.length >= qs.length) {
                     curid = qs.length - 1;
                     $('#msg').html('<span class="font14px">已经在上次完成此问卷，<br/>如此问卷并非您所填写，请至右上“重新填写”。</span>');
                 }
                 else {
                     $('#msg').html('<span class="font14px">您上次完成到第' + curid + '题，请继续填写。</span>');
                 }
             }

             //渲染当前题
             renderQuestion("");

             $('#prev').click(function () { renderQuestion("prev", false); });
             $('#next').click(function () { renderQuestion("next", false); });

             $('input[name="option"]').click(function () {
                 renderQuestion("next", true);
             });

             if ($.cookie(cookienm_secondpast) != undefined && $.cookie(cookienm_secondpast) != null) {
                 accessDate = accessDate - parseInt($.cookie(cookienm_secondpast)) * 1000;
             }

             setInterval(function () { $('#timepast').html('已用时' + getTimePast(accessDate) + "&nbsp;&nbsp;&nbsp;"); }, 1000);
             $('#reset').click(function () {
                 if (!confirm("此操作会清空之前您的填写，是否确认？")) { return; }
                 removeCookies();
                 document.location.href = document.location.href;
             });

         });
});